package com.indexingsystem.system.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.indexingsystem.boss.Vo.ResCategoryRelationsVo;
import com.indexingsystem.boss.Vo.SelectResDetailVO;
import com.indexingsystem.boss.admin.mapper.ResCategoryRelationsMapper;
import com.indexingsystem.boss.admin.mapper.ResourceCategorsMapper;
import com.indexingsystem.boss.admin.mapper.ResourceTypeMapper;
import com.indexingsystem.boss.admin.mapper.ResourceUpdateRecordMapper;
import com.indexingsystem.boss.admin.mapper.ResourcesMapper;
import com.indexingsystem.boss.common.Constants;
import com.indexingsystem.boss.entity.Books;
import com.indexingsystem.boss.entity.Games;
import com.indexingsystem.boss.entity.Magazines;
import com.indexingsystem.boss.entity.ResCategoryRelations;
import com.indexingsystem.boss.entity.ResourceCategors;
import com.indexingsystem.boss.entity.ResourceType;
import com.indexingsystem.boss.entity.ResourceUpdateRecord;
import com.indexingsystem.boss.entity.Resources;
import com.indexingsystem.boss.entity.Videos;
import com.indexingsystem.boss.utils.DateUtil;
import com.indexingsystem.boss.utils.InstitutionLoadUtils;
import com.indexingsystem.boss.utils.StringUtil;
import com.indexingsystem.db.mongoDB.impl.ResourceCategorsResListMongo;
import com.indexingsystem.db.mongoDB.po.ResourceCategorsResPo;
import com.indexingsystem.system.exception.BusinessException;
import com.indexingsystem.system.service.IArticlesService;
import com.indexingsystem.system.service.IBooksService;
import com.indexingsystem.system.service.IGamesService;
import com.indexingsystem.system.service.IMagazinesService;
import com.indexingsystem.system.service.IResCategoryRelationsService;
import com.indexingsystem.system.service.IResourceTypeService;
import com.indexingsystem.system.service.IVideosService;

@Service
public class ResCategoryRelationsServiceImpl implements IResCategoryRelationsService {

	@Resource
	private ResCategoryRelationsMapper	resCategoryRelationsMapper;
	@Resource
	private ResourceUpdateRecordMapper	resourceUpdateRecordMapper;
	@Resource
	private ResourceCategorsMapper		resourceCategorsMapper;

	@Resource
	private ResourcesMapper				resourcesMapper;

	@Resource
	private ResourceTypeMapper			resourceTypeMapper;

	@Resource
	private IResourceTypeService		iResourceTypeService;

	@Resource
	private IMagazinesService			magazinesService;

	@Resource
	private IBooksService				booksService;

	@Resource
	private IVideosService				videosService;

	@Resource
	private IGamesService				gamesService;

	@Resource
	private IArticlesService			articlesService;

	/**
	 * 根据资源分类与资源关系id解除关系.
	 * 
	 * @param resCategoryRelationId
	 * @return
	 */
	@Override
	public int deleteByPrimaryKey(String resCategoryRelationId) {

		ResCategoryRelations resCategoryRelations = resCategoryRelationsMapper.selectByPrimaryKey( resCategoryRelationId );
		if (StringUtil.isNotBlank( resCategoryRelations )) {
			// 删除mongo
			ResourceCategorsResListMongo.deleteResCategoryRelationsById( resCategoryRelations, InstitutionLoadUtils.getString( "institutionId" ) );
		}

		return resCategoryRelationsMapper.deleteByPrimaryKey( resCategoryRelationId );
	}

	/**
	 * 获取所有资源分类中有资源的资源分类id集合.
	 * 
	 * @return
	 */
	@Override
	public List<String> getResourceCategoryIdList() {
		return resCategoryRelationsMapper.getResourceCategoryIdList();
	}

	/**
	 * 通过资源分类id解除所有资源分类中资源关系.
	 * 
	 * @param resCategoryId
	 * @return
	 */
	@Override
	public int deleteResRelationByResCategoryId(String resCategoryId) {
		return resCategoryRelationsMapper.deleteResRelationByResCategoryId( resCategoryId );
	}

	/**
	 * 建立资源分类与资源的关系.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public int insertSelective(ResCategoryRelations record) {
		return resCategoryRelationsMapper.insert( record );
	}

	/**
	 * 通过资源分类id和资源id删除资源分类关系信息.
	 * 
	 * @param resCategoryRelations
	 * @return
	 */
	@Override
	public int deleteResRelationByResIdOrResCategoryId(ResCategoryRelations resCategoryRelations) {

		return resCategoryRelationsMapper.deleteResRelationByResIdOrResCategoryId( resCategoryRelations );
	}

	/**
	 * 批量新增资源分类中的资源关系.
	 * 
	 * @param resCategoryRelationsList
	 * @return
	 * @throws BusinessException
	 */
	public int insertResCategoryRelationsBatch(String request) throws BusinessException {
		int result = 0;
		List<ResCategoryRelations> resCategoryRelationsList = null;
		ResCategoryRelations resCategoryRelations = null;
		ResCategoryRelations resQueryCategoryRelations = null;
		Set<String> resSetList = null;
		ResourceCategors resourceCategors = null;
		Resources resources = null;
		ResourceType resourceType = null;
		List<ResCategoryRelations> resResultRelationsList = null;
		String resTable = "";
		List<ResourceCategorsResPo> resourceCategorsResPoList = null;
		if (StringUtils.isNotBlank( request )) {
			JSONObject jsonobject = JSONObject.fromObject( request );
			String resCategoryId = jsonobject.getString( "resCategoryId" );
			String resId = jsonobject.getString( "resId" );
			List<String> resIdList = JSONArray.toList( JSONArray.fromObject( resId ) );
			if (null != resIdList && resIdList.size() > 0) {
				resSetList = new HashSet<String>();
				for (String resIdVal : resIdList) {
					if (!resSetList.contains( resIdVal )) {
						resSetList.add( resIdVal );
					}
				}
			}
			List<String> resCategoryIdList = JSONArray.toList( JSONArray.fromObject( resCategoryId ) );
			if (null != resCategoryIdList && resCategoryIdList.size() > 0) {
				resCategoryRelationsList = new ArrayList<ResCategoryRelations>();
				if (null != resSetList && resSetList.size() > 0) {
					for (String resIdVal : resSetList) {
						resCategoryRelations = new ResCategoryRelations();
						resCategoryRelations.setResCategoryRelationId( StringUtil.createSystemDataPrimaryKey() );
						resCategoryRelations.setResCategoryId( resCategoryIdList.get( 0 ) );
						resCategoryRelations.setResId( resIdVal );
						resCategoryRelationsList.add( resCategoryRelations );
					}
				}
			}

			if (null != resCategoryRelationsList && resCategoryRelationsList.size() > 0) {
				resourceCategorsResPoList = new ArrayList<ResourceCategorsResPo>();
				for (ResCategoryRelations resCateRela : resCategoryRelationsList) {
					// 判断上级是否为连续出版物
					resourceCategors = resourceCategorsMapper.selectByPrimaryKey( resCateRela.getResCategoryId() );
					if (null != resourceCategors) {
						if (resourceCategors.getIsPublications() == 1) {// 如果是连续出版物
							resources = resourcesMapper.selectByPrimaryKey( resCateRela.getResId() );// 通过资源Id查询资源信息
							if (null != resources) {
								resourceType = resourceTypeMapper.selectByPrimaryKey( resources.getResTypeId() );// 通过资源类型Id查询资源名称
								if (null != resourceType) {
									resTable = resourceType.getResTable();
									if (!resTable.equals( "Magazines" ) && !resTable.equals( "mobile" )) {
										throw new BusinessException( Constants.IS_PUBLICATIONS );
									}
								}
							}
						} else {
							resources = resourcesMapper.selectByPrimaryKey( resCateRela.getResId() );// 通过资源Id查询资源信息
							if (null != resources) {
								resourceType = resourceTypeMapper.selectByPrimaryKey( resources.getResTypeId() );// 通过资源类型Id查询资源名称
								if (null != resourceType) {
									resTable = resourceType.getResTable();
									if (resTable.equals( "Magazines" )) {
										throw new BusinessException( Constants.IS_NOT_PUBLICATIONS );
									}

									if (resTable.equals( "mobile" )) {
										throw new BusinessException( Constants.IS_NOT_PUBLICATIONS );
									}

								}
							}
						}
					}
					// 如果存在就不新增，否则就新增
					resQueryCategoryRelations = new ResCategoryRelations();
					resQueryCategoryRelations.setResCategoryId( resCateRela.getResCategoryId() );
					resQueryCategoryRelations.setResId( resCateRela.getResId() );
					resResultRelationsList = resCategoryRelationsMapper.selectResCategoryRelByResId( resQueryCategoryRelations );
					if (resResultRelationsList.isEmpty()) {
						result = resCategoryRelationsMapper.insertResCategoryRelationsBatch( resCategoryRelationsList );
					}

					// 加入缓存
					ResourceCategorsResPo resourceCategorsResPo = new ResourceCategorsResPo();
					resourceCategors = resourceCategorsMapper.selectByPrimaryKey( resCateRela.getResCategoryId() );
					resources = resourcesMapper.selectByPrimaryKey( resCateRela.getResId() );// 通过资源Id查询资源信息

					ResourceType resourceTypeObj = iResourceTypeService.selectByPrimaryKey( resources.getResTypeId() );
					Magazines magazines = magazinesService.selectByPrimaryKey( resources.getResId() );
					if (resourceType.getResTable().equals( "Magazines" )) {
						resourceCategorsResPo.setThumbnail( magazines.getFrontCover() );
						resourceCategorsResPo.setResType( 1 );
						String publishDate = magazines.getYear() + "年" + magazines.getMonth() + "月" + "第" + magazines.getPeriodOfTime() + "期";

						String month = "";
						if (magazines.getMonth() < 10) {
							month = "0" + magazines.getMonth().toString();
							// dd = "01";
						} else {
							month = magazines.getMonth().toString();
						}

						String dateValue = magazines.getYear() + "-" + month + "-" + "01";
						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( dateValue ) );
						resourceCategorsResPo.setPublishDate( publishDate );

					} else if (resourceType.getResTable().equals( "Books" )) {
						Books books = booksService.selectByPrimaryKey( resources.getResId() );
						resourceCategorsResPo.setThumbnail( books.getFrontCover() );
						resourceCategorsResPo.setResType( 2 );
						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
					} else if (resourceType.getResTable().equals( "Videos" ) || resourceType.getResTable().equals( "Pictures" )) {
						Videos videos = videosService.selectByPrimaryKey( resources.getResId() );
						resourceCategorsResPo.setThumbnail( videos.getFrontCover() );
						resourceCategorsResPo.setResType( 2 );
						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
					} else if (resourceType.getResTable().equals( "Games" )) {
						Games games = gamesService.selectByPrimaryKey( resources.getResId() );
						resourceCategorsResPo.setThumbnail( games.getFrontCover() );
						resourceCategorsResPo.setResType( 2 );
						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
					} else if (resourceType.getResTable().equals( "Articles" )) {
						resourceCategorsResPo.setThumbnail( resources.getThumbnail() );
						resourceCategorsResPo.setResType( 2 );
						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
					}
					resourceCategorsResPo.setResId( resources.getResId() );
					resourceCategorsResPo.setResName( resources.getResName() );
					resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
					resourceCategorsResPo.setResTypeId( resources.getResTypeId() );
					resourceCategorsResPo.setResCategoryId( resourceCategors.getResCategoryId() );
					resourceCategorsResPo.setResCategoryName( resourceCategors.getResName() );
					resourceCategorsResPo.setResTable( resourceTypeObj.getResTable() );
					resourceCategorsResPo.setStatus( resources.getStatus() );

					if (!resourceCategorsResPoList.contains( resourceCategorsResPo )) {
						resourceCategorsResPoList.add( resourceCategorsResPo );
					}
				}
				// 存储更新到mongo
				if (null != resourceCategorsResPoList && resourceCategorsResPoList.size() > 0) {
					ResourceCategorsResListMongo.addResourceCategorsResList( resourceCategorsResPoList,
							InstitutionLoadUtils.getString( "institutionId" ) );
				}
			}
		}

		// 建立新的资源和资源分类关系 向记录表添加数据
		if (resCategoryRelationsList != null && resCategoryRelationsList.size() > 0) {
			for (int i = 0; i < resCategoryRelationsList.size(); i++) {
				SelectResDetailVO selectResDetailVO = this.resCategoryRelationsMapper.selectResDetail( resCategoryRelationsList.get( i )
						.getResCategoryRelationId() );
				if (selectResDetailVO != null) {
					ResourceUpdateRecord resourceUpdateRecord = new ResourceUpdateRecord();
					resourceUpdateRecord.setResourceUpdateRecordId( StringUtil.createSystemDataPrimaryKey() );
					resourceUpdateRecord.setResId( selectResDetailVO.getResId() );
					resourceUpdateRecord.setResTable( selectResDetailVO.getResTable() );
					resourceUpdateRecord.setResTypeId( selectResDetailVO.getResTypeId() );
					resourceUpdateRecord.setSuperCategoryId( selectResDetailVO.getParentId() );
					resourceUpdateRecord.setResourceCategoryId( selectResDetailVO.getResCategoryId() );
					resourceUpdateRecord.setOperatedate( DateUtil.getCurDate_YYYY_MM_DD() );
					resourceUpdateRecord.setState( "1" );
					this.resourceUpdateRecordMapper.insert( resourceUpdateRecord );
				}
			}
		}
		return result;
	}

	/**
	 * 批量修改资源分类中的资源关系.
	 * 
	 * @param
	 * @return
	 * @throws BusinessException
	 */
	@Override
	public int updateResCategoryRelationsBatch(String request) throws BusinessException {
		Integer result = 0;
		JSONObject jsonobject = JSONObject.fromObject( request );
		String resCategoryId = jsonobject.getString( "resCategoryId" );
		List<String> resCategoryIdList = JSONArray.toList( JSONArray.fromObject( resCategoryId ) );
		resCategoryRelationsMapper.deleteResRelationByResCategoryId( resCategoryIdList.get( 0 ) );
		List<ResCategoryRelations> resCategoryRelationsList = new ArrayList<ResCategoryRelations>();
		ResCategoryRelations resCategoryRelations = new ResCategoryRelations();
		Set<String> resSetList = new HashSet<String>();
		String resId = jsonobject.getString( "resId" );
		List<ResourceCategorsResPo> resourceCategorsResPoList = null;
		List<String> resIdList = JSONArray.toList( JSONArray.fromObject( resId ) );
		for (String resIdVal : resIdList) {
			resSetList.add( resIdVal );
		}
		for (String resIdVal : resSetList) {
			resCategoryRelations = new ResCategoryRelations();
			resCategoryRelations.setResCategoryRelationId( StringUtil.createSystemDataPrimaryKey() );
			resCategoryRelations.setResCategoryId( resCategoryIdList.get( 0 ) );
			resCategoryRelations.setResId( resIdVal );
			resCategoryRelationsList.add( resCategoryRelations );
		}
		ResourceCategors resourceCategors = new ResourceCategors();
		Resources resources = new Resources();
		ResourceType resourceType = new ResourceType();
		boolean is = false;
		for (int i = 0; i < resCategoryIdList.size(); i++) {
			// 判断上级是否为连续出版物
			resourceCategors = resourceCategorsMapper.selectByPrimaryKey( resCategoryIdList.get( 0 ) );
			if (resourceCategors.getIsPublications() == 1) {// 如果是连续出版物
				is = true;
			}
		}
		if (is) {
			for (int j = 0; j < resIdList.size(); j++) {// 只能添加报刊与文章资源
				resources = resourcesMapper.selectByPrimaryKey( resIdList.get( 0 ) );// 通过资源Id查询资源信息
				resourceType = resourceTypeMapper.selectByPrimaryKey( resources.getResTypeId() );
				if (!resourceType.getResTable().equals( "Magazines" ) && !resourceType.getResTable().equals( "mobile" )) {
					throw new BusinessException( Constants.IS_PUBLICATIONS );
				}
			}
		}
		result += resCategoryRelationsMapper.insertResCategoryRelationsBatch( resCategoryRelationsList );
		if (null != resCategoryRelationsList && resCategoryRelationsList.size() > 0) {
			resourceCategorsResPoList = new ArrayList<ResourceCategorsResPo>();
			for (ResCategoryRelations resCateRela : resCategoryRelationsList) {
				// 加入缓存
				ResourceCategorsResPo resourceCategorsResPo = new ResourceCategorsResPo();
				resourceCategors = resourceCategorsMapper.selectByPrimaryKey( resCateRela.getResCategoryId() );
				resources = resourcesMapper.selectByPrimaryKey( resCateRela.getResId() );// 通过资源Id查询资源信息

				ResourceType resourceTypeObj = iResourceTypeService.selectByPrimaryKey( resources.getResTypeId() );
				Magazines magazines = magazinesService.selectByPrimaryKey( resources.getResId() );
				if (resourceType.getResTable().equals( "Magazines" )) {
					resourceCategorsResPo.setThumbnail( magazines.getFrontCover() );
					resourceCategorsResPo.setResType( 1 );
					String publishDate = magazines.getYear() + "年" + magazines.getMonth() + "月" + "第" + magazines.getPeriodOfTime() + "期";

					String month = "";
					if (magazines.getMonth() < 10) {
						month = "0" + magazines.getMonth().toString();
						// dd = "01";
					} else {
						month = magazines.getMonth().toString();
					}

					String dateValue = magazines.getYear() + "-" + month + "-" + "01";
					resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( dateValue ) );
					resourceCategorsResPo.setPublishDate( publishDate );

				} else if (resourceType.getResTable().equals( "Books" )) {
					Books books = booksService.selectByPrimaryKey( resources.getResId() );
					resourceCategorsResPo.setThumbnail( books.getFrontCover() );
					resourceCategorsResPo.setResType( 2 );
					resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
					resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
				} else if (resourceType.getResTable().equals( "Videos" ) || resourceType.getResTable().equals( "Pictures" )) {
					Videos videos = videosService.selectByPrimaryKey( resources.getResId() );
					resourceCategorsResPo.setThumbnail( videos.getFrontCover() );
					resourceCategorsResPo.setResType( 2 );
					resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
					resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
				} else if (resourceType.getResTable().equals( "Games" )) {
					Games games = gamesService.selectByPrimaryKey( resources.getResId() );
					resourceCategorsResPo.setThumbnail( games.getFrontCover() );
					resourceCategorsResPo.setResType( 2 );
					resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
					resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
				} else if (resourceType.getResTable().equals( "Articles" )) {
					resourceCategorsResPo.setThumbnail( resources.getThumbnail() );
					resourceCategorsResPo.setResType( 2 );
					resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( resources.getPublishDate() ) );
					resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
				}
				resourceCategorsResPo.setResId( resources.getResId() );
				resourceCategorsResPo.setResName( resources.getResName() );
				resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
				resourceCategorsResPo.setResTypeId( resources.getResTypeId() );
				resourceCategorsResPo.setResCategoryId( resourceCategors.getResCategoryId() );
				resourceCategorsResPo.setResCategoryName( resourceCategors.getResName() );
				resourceCategorsResPo.setResTable( resourceTypeObj.getResTable() );
				resourceCategorsResPo.setStatus( resources.getStatus() );

				if (!resourceCategorsResPoList.contains( resourceCategorsResPo )) {
					resourceCategorsResPoList.add( resourceCategorsResPo );
				}
			}
			// 存储更新到mongo
			if (null != resourceCategorsResPoList && resourceCategorsResPoList.size() > 0) {
				ResourceCategorsResListMongo
						.addResourceCategorsResList( resourceCategorsResPoList, InstitutionLoadUtils.getString( "institutionId" ) );
			}
		}
		return result;
	}

	/**
	 * 批量删除资源分类已存在的数据.
	 * 
	 * @param resCategoryRelationsList
	 * @return
	 */
	@Override
	public int batchDeleteResCategoryRelations(ResCategoryRelations list) {
		return resCategoryRelationsMapper.batchDeleteResCategoryRelations( list );
	}

	/**
	 * 通过资源分类与资源关系id，查询资源详情.
	 * 
	 * @param resCategoryRelationId
	 * @return
	 */
	@Override
	public ResCategoryRelations selectByPrimaryKey(String resCategoryRelationId) {
		return resCategoryRelationsMapper.selectByPrimaryKey( resCategoryRelationId );
	}

	/**
	 * 通过资源id查询资源关系信息.
	 * 
	 * @param resId
	 * @return
	 */
	@Override
	public List<ResCategoryRelationsVo> getResCategoryRelationsByResId(String resId) {
		return resCategoryRelationsMapper.getResCategoryRelationsByResId( resId );
	}

	/**
	 * 修改资源分类与资源关系.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(ResCategoryRelations record) {
		return resCategoryRelationsMapper.updateByPrimaryKey( record );
	}

	/**
	 * 通过分类id和资源id结合查询返回资源分类关系.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public List<ResCategoryRelations> selectResCategoryRelationsInfo(ResCategoryRelations record) {
		return resCategoryRelationsMapper.selectResCategoryRelationsInfo( record );
	}

	/**
	 * 通过分类id和资源id结合查询返回资源分类关系.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public ResCategoryRelations selectResCategoryRelationsModelInfo(ResCategoryRelations record) {
		return resCategoryRelationsMapper.selectResCategoryRelationsModelInfo( record );
	}

	/**
	 * 通过资源分类id获取分类关联资源.
	 * 
	 * @param resCategoryId
	 * @return
	 */
	@Override
	public List<ResCategoryRelations> selectResCategoryRelByResCategoryId(String resCategoryId) {
		return resCategoryRelationsMapper.selectResCategoryRelByResCategoryId( resCategoryId );
	}

	/**
	 * 通过资源id查询资源分类与资源关联信息.
	 * 
	 * @param resCategoryRelations
	 * @return
	 */
	@Override
	public List<ResCategoryRelations> selectResCategoryRelByResId(ResCategoryRelations resCategoryRelations) {
		return resCategoryRelationsMapper.selectResCategoryRelByResId( resCategoryRelations );
	}

	@Override
	public SelectResDetailVO selectResDetail(String res_category_relation_id) {
		// TODO Auto-generated method stub
		return resCategoryRelationsMapper.selectResDetail( res_category_relation_id );
	}

	@Override
	public int deleteByPrimaryKeyByResId(String resId) throws Exception {
		// TODO Auto-generated method stub
		return resCategoryRelationsMapper.deleteByPrimaryKeyByResId( resId );
	}

}